package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.util.IdGenerator;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class VideoApiImpl implements VideoApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdGenerator idGenerator;


    @Override
    public PageResult findVideoList(Integer page, Integer pagesize, Long userId) {
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        query.with(Sort.by(Sort.Order.desc("created")));
        query.with(PageRequest.of(page - 1, pagesize));
        List<Video> videoList = mongoTemplate.find(query, Video.class);
        long count = mongoTemplate.count(query, Video.class);

        int pages = (int) Math.ceil(count * 1.0 / pagesize);
        return new PageResult((int) count, pagesize, pages, page, videoList);
    }

    @Override
    public String save(Video video) {
        //1. 补全信息
        video.setId(ObjectId.get());
        video.setCreated(System.currentTimeMillis());
        video.setVid(idGenerator.nextId("video"));

        mongoTemplate.save(video);
        return video.getId().toHexString();
    }

    @Override
    public void saveUserFocus(Long userId, Long targetId) {
        FollowUser followUser = new FollowUser();
        followUser.setUserId(userId);
        followUser.setFollowUserId(targetId);
        followUser.setId(ObjectId.get());
        followUser.setCreated(System.currentTimeMillis());

        mongoTemplate.save(followUser);
    }

    @Override
    public void removeUserFocus(Long userId, Long targetId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId)
                .and("followUserId").is(targetId));
        mongoTemplate.remove(query, FollowUser.class);
    }

    @Override
    public Video findById(String videoId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("videoId").is(new ObjectId(videoId))), Video.class);
    }

    @Override
    public List<Video> findListByPids(List<Long> vidList) {
        return mongoTemplate.find(Query.query(Criteria.where("vid").in(vidList)), Video.class);
    }

}